package com.probiz.estore.imports.handler.product;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;

public class CategorySimplePathNameHandler extends ColumnBasicHandler implements ColumnHandler{
	private Logger logger = Logger.getLogger(CategorySimplePathNameHandler.class);
	protected ProductCategoryManager	productCategoryManager	= null;
	public void setProductCategoryManager(ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}

	public void setProperty(ImportModel importModel, Column column)throws Exception {
		Product product=(Product)importModel.getTarget();
		
		ProductCategory category=null;
		if(StringUtils.isNotEmpty(column.getValue())){
			//case：有指定目录简单路径的，就搜索获得
			category=getCategoryByPathName(importModel,column.getValues().toArray(new String[]{}));
			if(importModel.getResult() == ImportModel.RESULT_ERROR){
				return ;
			}
			if(null != category){
				product.setCategory(category);
				product.setUseSimplePathName(true);
				importModel.setResult(ImportModel.RESULT_SUCCESS);
			}
		}
	}
	
	
	public ProductCategory getCategoryByPathName(ImportModel importModel,String categoryNames[]){
		Integer parentCategoryId=ProductCategory.ROOT_ID;
		ProductCategory parentCategory=productCategoryManager.getById(ProductCategory.ROOT_ID);
		for (String categoryName : categoryNames) {
			List<ProductCategory> categoryList=productCategoryManager.listCategoryByParentIdAndName(parentCategoryId, categoryName);
			if(0 == categoryList.size()){
				//设置结果
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "在目录【"+parentCategory.getCategoryName()+"】下找不到目录名称为【"+categoryName+"】的目录，无法导入";
				logger.error(msg);
				importModel.setMsg(msg);
				return null;
			}else if(1 == categoryList.size()){	
				parentCategory = categoryList.get(0);
				parentCategoryId = parentCategory.getCategoryId();
			}else{
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "在目录【"+parentCategory.getCategoryName()+"】下找到多个目录名称均为【"+categoryName+"】的目录，系统无法识别";
				logger.error(msg);
				importModel.setMsg(msg);
				return null;
			}
		}
		return parentCategory;
	}

	
	

}
